<template>
  <div class="top-navbar">
    <div class="navbar-left">
      <h1 class="app-title">HousingHub</h1>
    </div>
    <div class="navbar-center">
      <el-menu
        :default-active="activeIndex"
        mode="horizontal"
        @select="handleSelect"
        background-color="rgba(255, 255, 255, 0.1)"
        text-color="#fff"
        active-text-color="#4A90E2"
      >
        <el-menu-item index="1" @click="goToHome">首页</el-menu-item>
        <el-menu-item index="2" @click="goToSearch">房源搜索</el-menu-item>
        <el-menu-item index="3" @click="goToAgentDashboard" v-if="isAgent">中介工作台</el-menu-item>
        <el-menu-item index="3" @click="goToPublish" v-else>发布房源</el-menu-item>
        <el-menu-item index="4" @click="goToMessages">消息中心</el-menu-item>
      </el-menu>
    </div>
    <div class="navbar-right">
      <!-- 消息通知 -->
      <MessageNotification class="message-notification" />

      <!-- 用户下拉菜单 -->
      <el-dropdown @command="handleUserCommand">
        <span class="user-info">
          <el-avatar :size="32" :src="userInfo.avatar" />
          <span class="username">{{ userInfo.username || '用户' }}</span>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="profile">个人资料</el-dropdown-item>
            <el-dropdown-item command="settings">设置</el-dropdown-item>
            <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import MessageNotification from '@/components/message/MessageNotification.vue'
import { userLogout, getUserInfo } from '@/utils/auth'
import api from '@/utils/api'

const router = useRouter()
const props = defineProps({
  activeIndex: {
    type: String,
    default: '1'
  }
})

// 用户信息
const userInfo = reactive({
  username: '',
  avatar: '',
  email: '',
  role: null
})

// 检查用户是否为中介
const isAgent = computed(() => {
  return userInfo.role === 4 // 假设中介角色ID为4
})

// 顶部导航栏跳转
const goToHome = () => {
  router.push('/')
}

const goToSearch = () => {
  router.push('/house/search')
}

const goToPublish = () => {
  router.push('/house/publish')
}

const goToMessages = () => {
  router.push('/message')
}

const goToAgentDashboard = () => {
  router.push('/agent/dashboard')
}

// 用户命令处理
const handleUserCommand = async (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      try {
        await userLogout()
        ElMessage.success('退出登录成功')
        router.push('/login')
      } catch (error) {
        console.error('登出失败:', error)
        // 即使登出API失败，也要清除本地状态并跳转
        ElMessage.success('退出登录成功')
        router.push('/login')
      }
      break
  }
}

// 菜单选择处理
const handleSelect = (key) => {
  switch (key) {
    case '1':
      router.push('/')
      break
    case '2':
      router.push('/house/search')
      break
    case '3':
      router.push('/house/publish')
      break
    case '4':
      router.push('/message')
      break
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await api.get('/user/profile')
    if (response.data.code === '200') {
      const profileData = response.data.data

      // 设置默认头像
      if (!profileData.avatar) {
        profileData.avatar = profileData.gender === '女'
          ? 'https://housinghub-system.oss-cn-hangzhou.aliyuncs.com/avatar/%E5%A4%B4%E5%83%8F/%E5%A4%B4%E5%83%8F/03.png'
          : 'https://housinghub-system.oss-cn-hangzhou.aliyuncs.com/avatar/%E5%A4%B4%E5%83%8F/%E5%A4%B4%E5%83%8F/05.png'
      }

      Object.assign(userInfo, profileData)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 设置默认值
    userInfo.username = '用户'
    userInfo.avatar = 'https://housinghub-system.oss-cn-hangzhou.aliyuncs.com/avatar/%E5%A4%B4%E5%83%8F/%E5%A4%B4%E5%83%8F/%E8%B5%A0.png'
  }
}

// 监听用户信息更新事件
const handleUserInfoUpdate = (event) => {
  const updatedUserInfo = event.detail
  Object.assign(userInfo, updatedUserInfo)
}

// 组件挂载时获取用户信息并添加事件监听
onMounted(() => {
  fetchUserInfo()
  // 监听用户信息更新事件
  window.addEventListener('userInfoUpdated', handleUserInfoUpdate)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('userInfoUpdated', handleUserInfoUpdate)
})
</script>

<style scoped>
.top-navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 30px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.app-title {
  color: white;
  font-size: 24px;
  font-weight: 700;
  margin: 0;
}

.navbar-center {
  flex: 1;
  margin: 0 20px;
}

.navbar-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.message-notification {
  margin-right: 8px;
}

:deep(.el-menu--horizontal) {
  border: none;
  background: transparent !important;
}

:deep(.el-menu--horizontal .el-menu-item) {
  color: white;
  border: none;
}

:deep(.el-menu--horizontal .el-menu-item:hover) {
  background: rgba(255, 255, 255, 0.2) !important;
}

:deep(.el-menu--horizontal .el-menu-item.is-active) {
  color: #4A90E2 !important;
  border: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  color: white;
}

.username {
  font-size: 16px;
  font-weight: 500;
}

@media (max-width: 992px) {
  .app-title {
    display: none;
  }

  .navbar-center {
    display: none;
  }
}
</style>
